<template>
  <div class="bg-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入名称"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="componentDeployList" :show-overflow-tooltip="true" :stripe="true"
              @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="ID" prop="id"/>
      <el-table-column label="组件/程序名称" width="120" prop="name"/>
      <el-table-column label="启用状态" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 0" type="success">未监控</el-tag>
          <el-tag v-else-if="scope.row.status == 1" type="danger">监控中</el-tag>
          <el-tag v-else type="warning">监控关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="部署的主机ip" width="120" prop="dependence"/>
      <el-table-column label="组件的注意事项" width="120"  prop="remarks"/>
      <el-table-column label="日志存放目录" width="200" prop="targetDir">
        <template #default="scope">
          <div v-if="scope.row.targetDir">
            <div v-for="(el, idx) in scope.row.targetDir.split(',')" :key="idx">
              {{ el.split('/')[el.split('/').length - 1].split('.')[0] }}:{{ el }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="组件类型" prop="type">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 0" type="success">组件</el-tag>
          <el-tag v-else type="primary">程序</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="端口号" prop="port"/>
      <el-table-column label="主机id" prop="computerId"/>
      <el-table-column label="创建时间" prop="createTime">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作">
        <template #default="scope">
          <el-button icon="Edit" link plain
                     type="primary" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button icon="Delete" link plain
                     type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[3, 5, 7, 10]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end"
        @size-change="getList"
        @current-change="getList"
    />
  </div>

  <!-- 添加或修改主机 -->
  <el-dialog v-model="open" :title="title" append-to-body width="600px">
    <el-form ref="componentDeployRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="0">未监控</el-radio>
          <el-radio :value="1">监控中</el-radio>
          <el-radio :value="2">监控关闭</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="主机" prop="computerId">
        <el-select v-model="form.computerId" clearable filterable placeholder="请选择主机" @change="handleChange"
                   @remove-tag="form.dependence = null">
          <el-option
              v-for="item in computerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="组件的注意事项" prop="remarks">
        <el-input v-model="form.remarks" placeholder="请输入组件的注意事项" type="textarea"/>
      </el-form-item>
      <el-form-item label="日志存放目录" prop="targetDir">
          <el-select allow-create multiple v-model="form.targetDir" clearable filterable placeholder="请选择日志存放目录">
              <el-option v-for="item in dirList" :key="item.defaultPath" :label="item.defaultPath" :value="item.defaultPath" />
          </el-select>
      </el-form-item>
      <el-form-item v-if="false" label="组件类型" prop="type">
        <el-select v-model="form.type" clearable filterable placeholder="请选择组件类型">
          <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="端口号" prop="port">
        <el-input v-model="form.port" placeholder="请输入端口号" type="number"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script name="DeployInfo" setup>
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {
  addComponentDeploy,
  delComponentDeploy,
  exportComponentDeploy,
  getComponentDeploy,
  listComponentDeploy,
  updateComponentDeploy
} from "@/api/componentDeploy";
import { getDefaultDirList } from "@/api/componentCategory";

import {listAllComputer} from "@/api/computer";
import {parseTime} from "@/utils/utils";

const {proxy} = getCurrentInstance();

const props = defineProps({
  categoryId: {
    type: Number
  },
  type: {
    type: Number
  },
  itemName: {
    type: String
  },
  cId: {
    type: Number
  }
})

const computerList = ref([]);
const componentDeployList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const typeOptions = ref([
  {
    value: 0,
    label: "组件"
  },
  {
    value: 1,
    label: "程序"
  }
])

const data = reactive({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    categoryId: null,
    computerId: null,
  },
  rules: {
    name: [
      {required: true, message: "组件名不能为空", trigger: ["blur", "change"]}
    ],
    status: [
      {required: true, message: "启用状态不能为空", trigger: ["blur", "change"]}
    ],
    dependence: [
      {required: true, message: "部署的主机ip不能为空", trigger: ["blur", "change"]}
    ],
    remarks: [
      {required: true, message: "注意事项不能为空", trigger: ["blur", "change"]}
    ],
    targetDir: [
      {required: true, message: "日志存放目录不能为空", trigger: ["blur", "change"]}
    ],
    type: [
      {required: true, message: "组件类型不能为空", trigger: ["blur", "change"]}
    ],
    port: [
      {required: true, message: "端口号不能为空", trigger: ["blur", "change"]}
    ],
    computerId: [
      {required: true, message: "主机不能为空", trigger: ["blur", "change"]}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

// 获取默认日志存放目录
const dirList = ref([]);
const getDirList = () => {
  // 通过id获取组件分类名称
  getDefaultDirList({ name: props.itemName }).then(response => {
    const { data = [], code = undefined } = response;
    if (code === 0) {
      dirList.value = data;
    }
  });
}

// 查询销售订单列表
function getList() {
  if (props.categoryId) {
    queryParams.value.categoryId = props.categoryId
  }
  if (props.cId) {
    queryParams.value.computerId = props.cId
  }
  loading.value = true;
  listComponentDeploy(queryParams.value).then(response => {
    componentDeployList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    status: null,
    dependence: null,
    remarks: null,
    targetDir: null,
    type: props.type,
    port: null,
    tenantId: null,
    categoryId: props.categoryId,
    computerId: null,
    creator: null,
    createTime: null,
    updater: null,
    updateTime: null,
  };
  proxy.resetForm("componentDeployRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加组件";
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0]
  getComponentDeploy({id: id}).then(response => {
    form.value = response.data;
    if(form.value.targetDir){
      form.value.targetDir = form.value.targetDir.split(',');
    }
    open.value = true;
    title.value = "修改组件";
  });
}

// 提交按钮
function submitForm() {
  proxy.$refs["componentDeployRef"].validate(valid => {
    if (valid) {
      form.value.targetDir = form.value.targetDir.join(',');
      if (form.value.id != null) {
        updateComponentDeploy(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addComponentDeploy(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 批量删除按钮操作
function handleDelete(row) {
  const idList = (row.id ? [row.id] : null) || ids.value;
  proxy.$modal.confirm('是否确认删除组件"' + idList + '"的数据项？').then(function () {
    return delComponentDeploy({ids: idList.join(',')});
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  exportComponentDeploy(queryParams.value)
}

// 查询主机列表
function getAllComputer() {
  listAllComputer().then(response => {
    if (response.data) {
      computerList.value = response.data;
    }
  });
}

function handleChange(e) {
  computerList.value.forEach(item => {
    if (item.id === e) {
      form.value.dependence = item.ipAddress
    }
  })
}

onMounted( async() => {
  await getAllComputer();
  await getList();
  await getDirList();
});




</script>